﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Extensions;
using BLL;
using System.Globalization;
using System.Collections.Generic;

public partial class Product : System.Web.UI.Page
{
    
    private static int productId;
    private static string appPath;
    private int catId;
    private int index;
    private int brandId;

    /// <summary>
    /// Page's event handler
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(Request.QueryString["id"]))
            productId = Convert.ToInt32(Request.QueryString["id"]);
        else
            return;
        if (!String.IsNullOrEmpty(Request["index"]))
            index = Request["index"].ToInt32();
        if (!String.IsNullOrEmpty(Request["catId"]))
            catId = Request["catId"].ToInt32();
        if (!String.IsNullOrEmpty(Request["brandId"]))
            brandId = Request.QueryString["brandId"].ToInt32();
        appPath = Request.PhysicalApplicationPath;
        LoadProductDetails();
        if (Roles.IsUserInRole("Administrator"))
        {
            if (!IsPostBack)
                LoadForEdit();
        }
    }

    protected void EditButton_Click(object sender, EventArgs e)
    {
        LoadForEdit();
    }

    private void LoadForEdit()
    {
        ProductMV.ActiveViewIndex = 1;
        if (productId != 0)
        {
            using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
            {
                var p = db.Products.Single(c => c.ProductId == productId);
                BoundProductDetails(p);
            }
        }
    }

    /// <summary>
    /// View controller method
    /// </summary>
    /// <param name="p"></param>
    private void InitializeLabels(DAL.Product p)
    {
        ProductTitle.Text = p.Title;
        
        Page.Title = p.Title;
        ManufacturerTitle.Text = p.Brand.Title;
        WarrantyTime.Text = (p.Warranty == null) ? string.Empty : p.Warranty.Value;
        ShippingWeight.Text = p.ShippingWeight.ToString();
        ShippingCost.Text = p.ShippingCost.ToString();
        
        Price.Text = ((decimal) p.Price).ToMoneyString();
        DealerPrice.Text = p.DealerPrice.ToString();
        WholesaleDealerPrice.Text = p.DealerWholesalePrice.ToString();
        
        UserRating.CurrentRating = (p.Rating == null) ? 0 : (int) Math.Round((double)p.Rating);
        ProductDescriptionPanel.Text = p.Description;
        ProductFeaturesPanel.Text = p.Features;
        ProductSpecsPanel.Text = p.Specification;
        ImgGalery.ProductImageUrl = p.ProductImage.Url;
        ImgGalery.DefaultImageId = p.ProductImage.ImageId;
        ImgGalery1.ProductImageUrl = p.ProductImage.Url;
        ImgGalery1.DefaultImageId = p.ProductImage.ImageId;
        AvailabilityCheckLink.NavigateUrl = string.Format(AvailabilityCheckLink.NavigateUrl, p.ATTradeArticle);
    }

    /// <summary>
    /// View controller method
    /// </summary>
    private void LoadProductDetails()
    {
        if (productId != 0)
        {
            using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
            {
                var p = db.Products.Single(c => c.ProductId == productId);
                InitializeLabels(p);
            }
        }
    }

    protected string GetForwardLink()
    {
        string link = DAL.Product.GetForwardLink(index, catId, brandId);
        if (link == "#")
            return link;
        else
            return string.Format("Product.aspx{0}", link);
    }

    protected string GetBackLink()
    {
        string link = DAL.Product.GetBackLink(index, catId, brandId);
        if (link == "#")
            return link;
        else
            return string.Format("Product.aspx{0}", link);
    }
    protected void BuyButton_Click(object sender, ImageClickEventArgs e)
    {
        DAL.Product product = DAL.Product.GetProductByID(productId);
        Profile.ShoppingCart.InsertItem(product.ProductId, product.Title, (decimal) product.Price);
        Response.Redirect("ShoppingCart.aspx", false);
    }

    #region ProductEdit
    /// <summary>
    /// View controller method
    /// </summary>
    //private void LoadProductDetails()
    //{
    //    if (productId != 0)
    //    {
    //        using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
    //        {
    //            var p = db.Products.Single(c => c.ProductId == productId);
    //            BoundProductDetails(p);
    //        }
    //    }
    //}

    /// <summary>
    /// View controller method
    /// </summary>
    /// <param name="p"></param>
    private void BoundProductDetails(DAL.Product p)
    {
        ManufacturerTitleEdit.Text = (p.Brand == null) ? string.Empty : p.Brand.Title;
        WarrantyTimeEdit.Text = (p.Warranty == null) ? string.Empty : p.Warranty.Value;
        ShippingWeightEdit.Text = p.ShippingWeight.ToString();
        ShippingCostEdit.Text = p.ShippingCost.ToString();
        PriceEdit.Text = p.Price.ToString();
        DealerPriceEdit.Text = p.DealerPrice.ToString();
        WholesaleDealerPriceEdit.Text = p.DealerWholesalePrice.ToString();
        DescriptionEditor.Text = string.IsNullOrEmpty(p.Description) ? string.Empty : p.Description;
        SpecsEditor.Text = string.IsNullOrEmpty(p.Specification) ? string.Empty : p.Specification;
        FeaturesEditor.Text = string.IsNullOrEmpty(p.Features) ? string.Empty : p.Features;
        FeaturedCheckBox.Checked = (p.Featured == null) ? false : (bool)p.Featured;
        CategoryTextBox.Text = p.Category.Title;
        CategoryIdField.Value = p.CategoryId.ToString();
        ProductTitleEdit.Text = p.Title;
        UserRating.CurrentRating =
                        (p.ProductReviews.Count == 0) ? 0 :
                        (int)p.ProductReviews.Average(c => c.Rating);
        BLL.MenuManager mManager = new MenuManager();
        XMLMenu.Data = mManager.BuildXMLMenu("setCategory").ToString();
    }

    private void SaveProduct()
    {
        if (productId != 0)
        {
            using (DAL.EShopDBDataContext db = new DAL.EShopDBDataContext())
            {
                var product = db.Products.Single(c => c.ProductId == productId);
                product.SetBrand(ManufacturerTitleEdit.Text);
                product.SetWarranty(WarrantyTimeEdit.Text);
                product.ShippingWeight = ShippingWeightEdit.Text.GetDoubleOrNull();
                product.ShippingCost = ShippingCostEdit.Text.GetDecimalOrNull();
                product.Price = PriceEdit.Text.GetDecimalOrNull();
                product.DealerPrice = DealerPriceEdit.Text.GetDecimalOrNull();
                product.DealerWholesalePrice = WholesaleDealerPriceEdit.Text.GetDecimalOrNull();
                product.Description = DescriptionEditor.Text;
                product.Specification = SpecsEditor.Text;
                product.Features = FeaturesEditor.Text;
                product.Title = ProductTitleEdit.Text;
                product.CategoryId = CategoryIdField.Value.ToInt32();
                product.Featured = FeaturedCheckBox.Checked;
                db.SubmitChanges();
            }
        }
        
    }

    protected void AddPictureButton_Click(object sender, ImageClickEventArgs e)
    {
        //DAL.ProductImage productImage = new DAL.ProductImage();
        //productImage.AddImageToProduct(productId, Request.PhysicalApplicationPath, PictureUpload.PostedFile);
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        SaveProduct();
        ProductMV.ActiveViewIndex = 0;
        //LoadProductDetails();
        LoadForEdit();
    }

    #region Services (DeleteImage, MakeDefaultImage)

    [System.Web.Services.WebMethod]
    public static void MakeDefaultImage(int imageId)
    {
        DAL.Product.MakeDefaultImage(imageId, productId);
    }

    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static void DeleteImage(int imageId)
    {
        DAL.Product.DeleteImage(imageId, productId, appPath);
    }

    #endregion

    protected void SaveAndBackButton_Click(object sender, ImageClickEventArgs e)
    {
        SaveProduct();
        string link = GetBackLink();
        if (link != "#")
            Response.Redirect(link);
    }
    protected void SaveAndContinueButton_Click(object sender, ImageClickEventArgs e)
    {
        SaveProduct();
        string link = GetForwardLink();
        if (link != "#")
            Response.Redirect(link);
    }
    #endregion
}
